import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';

import { getUserInfoApi, loginApi, logoutApi } from '#/api';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();
  const loginLoading = ref(false);

  /**
   * 基于角色判断是否有权限
   * @description: Determine whether there is permission，The role is judged by the user's role
   * @param roles
   */
  function hasAccessByRoles(roles: string[]) {
    const userRoleSet = new Set(userStore.userRoles);
    const intersection = roles.filter((item) => userRoleSet.has(item));
    return intersection.length > 0;
  }

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const {
        data: { token },
      } = await loginApi(params);

      // 如果成功获取到 accessToken
      if (token) {
        // 将 accessToken 存储到 accessStore 中
        accessStore.setAccessToken(token);

        // 获取用户信息并存储到 accessStore 中
        // const [fetchUserInfoResult, accessCodes] = await Promise.all([
        //   fetchUserInfo(),
        //   getAccessCodesApi(),
        // ]);
        const fetchUserInfoResult = await fetchUserInfo();

        userInfo = fetchUserInfoResult;

        userStore.setUserInfo(userInfo);
        // accessStore.setAccessCodes(accessCodes);
        // accessStore.setAccessCodes(['AC_100100']);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(userInfo?.homePath || DEFAULT_HOME_PATH);
        }

        if (userInfo?.user_nickname) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.user_nickname || userInfo?.user_login}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  /**
   * 异步处理第三方登录
   * @param token
   * @param userInfo
   * @returns
   */
  async function thirdPartyLogin(token: string) {
    let userInfo: null | UserInfo = null;
    // 如果成功获取到 accessToken
    if (token) {
      // 将 accessToken 存储到 accessStore 中
      accessStore.setAccessToken(token);

      // 获取用户信息并存储到 accessStore 中
      const fetchUserInfoResult = await fetchUserInfo();

      userInfo = fetchUserInfoResult;

      userStore.setUserInfo(userInfo);

      if (accessStore.loginExpired) {
        accessStore.setLoginExpired(false);
      } else {
        await router.push(userInfo?.homePath || DEFAULT_HOME_PATH);
      }

      if (userInfo?.user_nickname) {
        notification.success({
          description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.user_nickname || userInfo?.user_login}`,
          duration: 3,
          message: $t('authentication.loginSuccess'),
        });
      }
    }
    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    // 因为接口必须传token才能退出成功，所以要先判断是否有token，否则会无限请求
    if (accessStore.accessToken) {
      try {
        await logoutApi();
      } catch {
        // 不做任何处理
      }
    }

    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: null | UserInfo = null;
    const { data } = await getUserInfoApi();
    if (data.roles) {
      const roles: number[] = data.roles.map((item: any) => item.id);

      data.user.roles =
        roles.includes(data.role_ids) || data.user.id === 1
          ? ['super']
          : ['admin'];
    }
    userInfo = data.user;
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    hasAccessByRoles,
    thirdPartyLogin,
    logout,
  };
});
